package com.lb.trac.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XmlTableTransformerParser extends DefaultHandler{

	private Set<XmlColumnWrapper> columnsInfo = new TreeSet<XmlColumnWrapper>();
	private String tableName;
	private InputStream is;
	private boolean foundTag=false;
	
	public XmlTableTransformerParser(String tableName){
		this.tableName=tableName;
	}
	public XmlTableTransformerParser(){
	}
	
	public XmlColumnWrapper[] parse() throws ParserConfigurationException, SAXException, IOException{
		SAXParserFactory parserFactory = SAXParserFactory.newInstance();
		SAXParser parser = parserFactory.newSAXParser();
		is = XmlTableTransformerParser.class.getResourceAsStream("/com/setup/trac/web/etc/beans-mapper.xml");
		parser.parse(is, this);
		return columnsInfo.toArray(new XmlColumnWrapper[0]);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(qName.equalsIgnoreCase("table")){
			foundTag=false;
		}
		super.endElement(uri, localName, qName);
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		String tagName = qName;
		if(tagName.equalsIgnoreCase("table")){
			String id = attributes.getValue("id");
			if(id.equalsIgnoreCase(tableName)){
				foundTag=true;
			}
			
		}
		if(foundTag && tagName.equalsIgnoreCase("column")){
			XmlColumnWrapper c = new XmlColumnWrapper(Integer.parseInt(attributes.getValue("order")),attributes.getValue("name"),attributes.getValue("property"));
			columnsInfo.add(c);
		}
		super.startElement(uri, localName, qName, attributes);
	}
	
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		XmlTableTransformerParser t = new XmlTableTransformerParser("USERS");
		t.parse();
	}
	public String getTableName() {
		return tableName;
	}
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	
}
